import msgpasser;
from msg import *;
import sys;
import os;
from CheckIn import check_in
from CheckOut import check_out
from QueryUsers import query_users
from CacheMessage import cache_message
from GetMessage import get_messages_front_end

name = raw_input('Enter mp name: ');
s=os.path.dirname(sys.argv[0]);
mp=msgpasser.messagePasser(name,'l');
msgpasser.mp = mp;
mp.thisName = name
#print "";
#print "--------------"
#print "Cirl+C works"
#print "--------------"

try:
    while(1):
        #print "True(Show alive) or False(Not show alive)"
        c = raw_input('Press "q" for quit/  "s" to send any message/  "c" for checkin message/ "o" for check_out "u" for query_users : ');
        print ""
        if c=='F':
            msgpasser.showAliveMessage = False
            print "Show alive off"
        if c=='T':
            msgpasser.showAliveMessage = True
            print "Show alive on"
        if c=='Q':
            msgpasser.sendalivethreadstate=False
            mp.recethread.server.shutdown()
            sys.exit(0);
        if c=='q':
            msgpasser.sendalivethreadstate=False;
            mp.recethread.server.shutdown()
            sys.exit(0);
        if c=='send_low_level':
            src=name;
            dest = []
            while True:
                try:
                    n = int(raw_input('Enter dest number: '))
                    break;
                except:
                    print "Enter a int!"
            for i in range(0, n):
                x = raw_input('Enter the dest: ')
                dest.append(x);
            data = raw_input('Data: ');
            mtype = raw_input('Type: ');
            newmsg= Message(src,dest,'time',data,mtype,None);
            print "sending message:";
            print newmsg;
            print mp.send(newmsg);

        if c=='p':
            print mp.messageRecord;
        if c=='c' :
            userName = raw_input('Enter the userName: ')
            status = raw_input('Enter the status: ')
            available = raw_input('Enter availability in int: ')
            check_in (mp, userName, 1, status, available)
        if c=='o' :
            userName = raw_input('Enter the userName: ')
            check_out(mp, userName)
        if c=='u' :
            print query_users()
        if c=='s' :
            fromName = raw_input('Enter the fromName: ')
            toName = raw_input('Enter the toName: ')
            messageText = raw_input('Enter the message: ')
            cache_message(mp, fromName, toName, messageText, 1)
        if c=='g' :
            forName = raw_input('Get the messages for userName: ')
            get_messages_front_end(mp, forName, mp.thisName)
except KeyboardInterrupt:
    print "In handler. Wait 5s to quit...."
    msgpasser.sendalivethreadstate=False
    mp.recethread.server.shutdown()
    sys.exit(0)
